<?php

namespace app\hook\controller;

use app\common\controller\Api;
use think\Db;
use think\facade\Env;
use think\facade\Log;
/**
 * hook接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**   Hook事件
    保活上报             on_server_keepalive
    流量事件             on_flow_report
    http文件鉴权事件      on_http_access
    播放鉴权事件          on_play
    推流鉴权事件          on_publish
    mp4切片录好事件       on_record_mp4
    ts切片录好事件        on_record_ts
    rtp服务超时事件       on_rtp_server_timeout
    rtsp播放鉴权事件      on_rtsp_auth
    rtsp专属鉴权事件      on_rtsp_realm
    发送rtp被动关闭       on_send_rtp_stopped
    服务启动事件          on_server_started
    服务关闭事件          on_server_exited
    telnet调试鉴权事件    on_shell_login
    流注册或注销事件       on_stream_changed
    无人观看流事件        on_stream_none_reader
    播放未找到流事件      on_stream_not_found
     *
     */
    /*
on_server_keepalive=http://192.168.0.55/hook/index/on_server_keepalive
on_flow_report=http://192.168.0.55/hook/index/on_flow_report
on_http_access=http://192.168.0.55/hook/index/on_http_access
on_play=http://192.168.0.55/hook/index/on_play
on_publish=http://192.168.0.55/hook/index/on_publish
on_record_mp4=http://192.168.0.55/hook/index/on_record_mp4
on_record_ts=http://192.168.0.55/hook/index/on_record_ts
on_rtp_server_timeout=http://192.168.0.55/hook/index/on_rtp_server_timeout
on_rtsp_auth=
on_rtsp_realm=
on_send_rtp_stopped=http://192.168.0.55/hook/index/on_send_rtp_stopped
on_server_started=http://192.168.0.55/hook/index/on_server_started
on_server_exited=http://192.168.0.55/hook/index/on_server_exited
on_shell_login=
on_stream_changed=http://192.168.0.55/hook/index/on_stream_changed
on_stream_none_reader=http://192.168.0.55/hook/index/on_stream_none_reader
on_stream_not_found=http://192.168.0.55/hook/index/on_stream_not_found

    */


    public function index()
    {
        $post= $this->request->post();

        $this->hookSuccess('请求成功',$post);
    }

    /**
     * 保活上报
     */
    public function on_server_keepalive()
    {
        $post= $this->request->post();
        customLog('on_server_keepalive',$post,'hook');
        $this->hookSuccess('success');
    }
    /**
     * 流量事件
     */
    public function on_flow_report()
    {
        $post= $this->request->post();
        customLog('on_flow_report',$post,'hook');
        $this->hookSuccess('success');
    }
    /**
     *  http文件鉴权事件
     */
    public function on_http_access()
    {
        $post= $this->request->post();
        customLog('on_http_access',$post,'hook');
        $this->hookSuccess('success');
    }
    /**
     * 播放鉴权
     *
     * array (
    'app' => 'fpv',
    'hook_index' => '5',
    'id' => '702-31',
    'ip' => '192.168.0.151',
    'mediaServerId' => 'fpv_live_sever_01',
    'params' => 'auth_key=vHuy65nV7yIcOtMFBp1RT6qkrLig1+mUI4tN1GUGDgPPp+Mm3hgRzg',
    'port' => '22780',
    'protocol' => 'http',
    'schema' => 'rtmp',
    'stream' => 'fcs1',
    'vhost' => '__defaultVhost__',
    )
     */
    public function on_play()
    {
        $post= $this->request->post();
        Log::debug('hook_play');
        Log::debug($post);
        if(!empty($post))
        {
            if(!empty($post['params']))
            {
                //这里验证 webrtc 中 参数 例如 "app=fpv&stream=fcs1&type=play&auth_key=bGUvye8DHeym3/sVTD49vAfvvQ2zn9Hd1quT52+W5hblXw&session=88-88"
                if (preg_match("/&/",$post['params'])) {

                    $arr = explode("&",str_replace('&amp;', '&', $post['params']));
                    $matches = preg_grep('/^auth_key=/', $arr);
                    if (!empty($matches)) {
                        //TD(current($matches)); // 输出：auth_key=bGUvye8DHeym3/sVTD49vAfvvQ2zn9Hd1quT52+W5hblXw
                        $auth_key_arr = explode("=",current($matches));
                    }
                    else
                    {
                        $this->hooKError('webrtc params auth_key decryption failed');
                    }
                } else {
                    $auth_key_arr = explode("=", $post['params']);
                }

                $auth_key = $auth_key_arr[1]??'';
                if(!empty($auth_key))
                {
                    //$timeStamp = Env::get('liveserver.timestamp');

                    //$push_key = Env::get('liveserver.push_key');

                    $play_key = Env::get('liveserver.play_key');
                    $play_auth_key = encrypt($auth_key,'D',Env::get('liveserver.encrypt_key'));
                    //Log::debug($play_auth_key);
                    if(!empty($play_auth_key))
                    {
                        $key_arr = explode("-", $play_auth_key);
                        //Log::debug($key_arr);
                        if(!empty($key_arr) && is_array($key_arr))
                        {
                            if($key_arr[0] == '/'.$post['app'].'/'.$post['stream'] && $key_arr[4] == $play_key && is_numeric($key_arr[5]) && is_numeric($key_arr[6]) && is_numeric($key_arr[7]))
                            {
                                $live = Db::name('live')->where([['app_id','=',$key_arr[5]],['user_id','=',$key_arr[7]],['id','=',$key_arr[6]]])->find();
                                if(!empty($live))
                                {
                                    $this->hookSuccess('play auth success');
                                }
                                else
                                {
                                    $this->hooKError('auth fail');
                                }
                            }
                            else
                            {
                                $this->hooKError('auth rule mismatched');
                            }
                        }
                        else
                        {
                            $this->hooKError('auth_key value failed');
                        }
                    }
                    else
                    {
                        $this->hooKError('auth_key decryption failed');
                    }

                }
                else
                {
                    $this->hooKError('auth_key null');
                }

            }
            else
            {
                $this->hooKError('params null');
            }
        }
        else
        {
            $this->hooKError('request null');
        }
    }

    /**
     * 推流鉴权
     *
     * array (
    'app' => 'fpv',
    'hook_index' => 7,
    'id' => '820-46',
    'ip' => '192.168.0.151',
    'mediaServerId' => 'fpv_live_sever_01',
    'originType' => 1,
    'originTypeStr' => 'rtmp_push',
    'params' => 'auth_key=7H22usva6yEcL9oAXZ5fE/3q76S9yvSJYM4M1j1HUAPPp+Mm3g',
    'port' => 25190,
    'protocol' => 'rtmp',
    'schema' => 'rtmp',
    'stream' => 'fcs1',
    'vhost' => '__defaultVhost__',
    )
     */
    public function on_publish()
    {
        $post= $this->request->post();
        Log::debug('hook_publish');
        Log::debug($post);
        if(!empty($post))
        {
            if(!empty($post['params']))
            {
                $auth_key_arr = explode("=", $post['params']);
                $auth_key = $auth_key_arr[1]??'';
                if(!empty($auth_key))
                {
                    //$timeStamp = Env::get('liveserver.timestamp');

                    $push_key = Env::get('liveserver.push_key');

                    //$play_key = Env::get('liveserver.play_key');
                    $push_auth_key = encrypt($auth_key,'D',Env::get('liveserver.encrypt_key'));
                    if(!empty($push_auth_key))
                    {
                        $key_arr = explode("-", $push_auth_key);
                        if(!empty($key_arr) && is_array($key_arr))
                        {
                            if($key_arr[0] == '/'.$post['app'].'/'.$post['stream'] && $key_arr[4] == $push_key && is_numeric($key_arr[5]) && is_numeric($key_arr[6]) && is_numeric($key_arr[7]))
                            {
                                $live = Db::name('live')->where([['app_id','=',$key_arr[5]],['user_id','=',$key_arr[7]],['id','=',$key_arr[6]]])->find();
                                if(!empty($live))
                                {
                                    $this->hookSuccess('publish auth success');
                                }
                                else
                                {
                                    $this->hooKError('auth fail');
                                }
                            }
                            else
                            {
                                $this->hooKError('auth rule mismatched');
                            }
                        }
                        else
                        {
                            $this->hooKError('auth_key value failed');
                        }
                    }
                    else
                    {
                        $this->hooKError('auth_key decryption failed');
                    }


                }
                else
                {
                    $this->hooKError('auth_key null');
                }

            }
            else
            {
                $this->hooKError('params null');
            }
        }
        else
        {
            $this->hooKError('request null');
        }


    }
    /**
     *  mp4切片录好事件
     */
    public function on_record_mp4()
    {
        $post= $this->request->post();
        customLog('on_record_mp4',$post,'hook');
        $this->hookSuccess('success');
    }
    /**
     *  ts切片录好事件
     */
    public function on_record_ts()
    {
        $post= $this->request->post();
        customLog('on_record_ts',$post,'hook');
        $this->hookSuccess('success');
    }

    /**
     *  rtp服务超时事件
     */
    public function on_rtp_server_timeout()
    {
        $post= $this->request->post();
        customLog('on_rtp_server_timeout',$post,'hook');
        $this->hookSuccess('success');
    }
    /**
     *  发送rtp被动关闭
     */
    public function on_send_rtp_stopped()
    {
        $post= $this->request->post();
        customLog('on_send_rtp_stopped',$post,'hook');
        $this->hookSuccess('success');
    }
    /**
     *  服务启动事件
     */
    public function on_server_started()
    {
        $post= $this->request->post();
        customLog('on_server_started',$post,'hook');
        $this->hookSuccess('success');
    }
    /**
     *  服务关闭事件
     */
    public function on_server_exited()
    {
        $post= $this->request->post();
        customLog('on_server_exited',$post,'hook');
        $this->hookSuccess('success');
    }




    /**
     * 流注册或注销事件
     *
     */
    public function on_stream_changed()
    {
        $post= $this->request->post();
        Log::debug('hook_changed');
        Log::debug($post);
        if(!empty($post))
        {

            $auth_key_arr = explode("=", $post['params']);
            $auth_key = $auth_key_arr[1]??'';
            if(!empty($auth_key))
            {
                $live = Db::name('live')->where([['stream', '=', $post['stream']]])->field('id')->find();
                if (!empty($live)) {
                    $update['update_time'] = date('Y-m-d H:i:s');
                    if ($post['regist'] == true) {
                        $update['live_status'] = '1';
                    } else {
                        $update['live_status'] = '2';
                    }
                    Db::name('live')->where([['id', '=', $live['id']]])->update($update);

                }
            }
        }
        $this->hookSuccess('success');
    }

    /**
     *  无人观看流事件
     */
    public function on_stream_none_reader()
    {
        $post= $this->request->post();
        customLog('on_stream_none_reader',$post,'hook');
        $this->hookSuccess('success');
    }
    /**
     *  播放未找到流事件
     */
    public function on_stream_not_found()
    {
        $post= $this->request->post();
        customLog('on_stream_not_found',$post,'hook');
        $this->hookSuccess('success');
    }


}
